/**
 * 
 */
package org.nielin.bestwaper.core;

import java.io.IOException;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nielin.wap.beans.ConstantsBean;
import org.nielin.util.config.SystemConf;
import org.nielin.util.log.MyLogger;
import org.nielin.util.profiling.UtilTimerStack;

/**
 * @author rockydai
 *
 */
public class Dispatcher extends HttpServlet {
        
    /**
     * 
     */
    private static final long serialVersionUID = -2312042807153819424L;
    public static final String PARAM_PAGE_ID = "id";
	private static final String PAGE_MISS_ID = "pageMiss";		
	private static boolean m_s_bGlobalVarIsSetted = false;	// 全局变量是否已经被设置	
	
	public void init(FilterConfig arg0) throws ServletException {
        try {
    		// God初始化
    		God.getInstance().startWorld();

        }
        catch( Exception e ) {
            MyLogger.getNormal().fatal("start world fail on Dispatcher!", e);
            throw new ServletException( "start world fail", e );
        }
	}	

	public void destroy() {
		God.getInstance().stopWorld();
	}
	
	/**
	 * 获得页面中的id
	 * @param req
	 * @param res
	 * @return 
	 */
	public static String getForwardId(HttpServletRequest req, HttpServletResponse res)
	{
		try
		{
			String id = req.getParameter(PARAM_PAGE_ID);
			
			if(id == null)    //传到server,但没有aid,跳到提示页
			{
				MyLogger.getNormal().warn("id is null, queryString:" + req.getQueryString());
				return PAGE_MISS_ID;
			}
			return id;
		}
		catch(Exception e)
		{
			MyLogger.getNormal().warn("NmsServer.getForwardId error", e);
			return PAGE_MISS_ID;
		}
	}	
	
	private void process(HttpServletRequest req, HttpServletResponse res)
	{
        // 设置全局变量
		if ( !m_s_bGlobalVarIsSetted )
		{
			MyLogger.getNormal().info( "set global vars!" );
			this.getServletContext().setAttribute( "g_sCommonTitle", SystemConf.getInstance().getCommonTitle() );
            this.getServletContext().setAttribute( "g_sImgBaseUrl", SystemConf.getInstance().getImgBaseUrl() );
            this.getServletContext().setAttribute( "constantsBean", new ConstantsBean());
			m_s_bGlobalVarIsSetted = true;
		}	
        
		WebEntity dest;
		WebEntityContext context;

        String id = getForwardId(req, res);
		
        dest = DispatcherMap.getInstance().getEntity( id );
        if ( dest == null )
        {
            MyLogger.getNormal().error( "id[" + id + "] is not exist!");
            dest = DispatcherMap.getInstance().getEntity(PAGE_MISS_ID);
            req.setAttribute( "missId", id );
            if ( dest == null )
            {
                ErrorPageBean errorpage = new ErrorPageBean("内部错误");
                MyLogger.getNormal().error("[" + errorpage.getErrno() + "]page miss page id[" + PAGE_MISS_ID + "] has not existed!");
                Dispatcher.toErrorPage(req, res, errorpage);
                return;
            }
        }
        
        context = new WebEntityContext();
        context.setRequest( req );
        context.setResponse( res );
        context.setId(id);		    

        String profileMsg = "WebEntity.go, id[" + dest.getId() + "]";
        UtilTimerStack.push(profileMsg);
        dest.go( context );     
        UtilTimerStack.pop(profileMsg);
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
		process(req, res);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException 
	{
		process(req, res);
	}
    
    public static void toStopPlayPage( HttpServletRequest req, HttpServletResponse res )
    {
        WebEntity dest = DispatcherMap.getInstance().getEntity( new ConstantsBean().STOP_PLAY_ID );
        if ( dest == null )
        {
            MyLogger.getNormal().error( "id[" + new ConstantsBean().STOP_PLAY_ID + "] is not exist!");
            dest = DispatcherMap.getInstance().getEntity(PAGE_MISS_ID);
            if ( dest == null )
            {
                MyLogger.getNormal().error( "page miss page id[" + PAGE_MISS_ID + "] has not existed!");
                return;
            }
        }
        
        WebEntityContext context = new WebEntityContext();
        context.setRequest( req );
        context.setResponse( res );
        dest.go( context );
    }
	
    public static void toErrorPage( HttpServletRequest req, HttpServletResponse res, ErrorPageBean errPage )
    {
        WebEntity dest = DispatcherMap.getInstance().getEntity( new ConstantsBean().ERROR_REDIRECT_ID );
        if ( dest == null )
        {
            MyLogger.getNormal().error( "id[" + new ConstantsBean().ERROR_REDIRECT_ID + "] is not exist!");
            dest = DispatcherMap.getInstance().getEntity(PAGE_MISS_ID);
            if ( dest == null )
            {
                MyLogger.getNormal().error( "page miss page id[" + PAGE_MISS_ID + "] has not existed!");
                return;
            }
        }
        
        req.setAttribute("errPage", errPage);
        
        WebEntityContext context = new WebEntityContext();
        context.setRequest( req );
        context.setResponse( res );
        dest.go( context );
    }

    /**
     * 登录信息失效时的错误提示页面
     * @param req
     * @param res
     * @param errMsg
     */
    public static void toErrorPage( HttpServletRequest req, HttpServletResponse res, String errMsg )
    {
        String errorEntityId =  new ConstantsBean().ERROR_REDIRECT_ID_NOT_LOGIN;
        WebEntity dest = DispatcherMap.getInstance().getEntity( errorEntityId );
        if ( dest == null )
        {
            MyLogger.getNormal().error( "id[" + new ConstantsBean().ERROR_REDIRECT_ID_NOT_LOGIN + "] is not exist!");
            dest = DispatcherMap.getInstance().getEntity(PAGE_MISS_ID);
            if ( dest == null )
            {
                MyLogger.getNormal().error( "page miss page id[" + PAGE_MISS_ID + "] has not existed!");
                return;
            }
        }

        req.setAttribute("errMsg", errMsg);

        WebEntityContext context = new WebEntityContext();
        context.setRequest( req );
        context.setResponse( res );
        context.setId(errorEntityId);
        dest.go( context );
    }    
    
    public static void toUserErrorPage( HttpServletRequest req, HttpServletResponse res, String errMsg )
    {
        String errorEntityId =  new ConstantsBean().USER_ERROR_REDIRECT_ID;
        WebEntity dest = DispatcherMap.getInstance().getEntity( errorEntityId );
        if ( dest == null )
        {
            MyLogger.getNormal().error( "id[" + new ConstantsBean().USER_ERROR_REDIRECT_ID + "] is not exist!");
            dest = DispatcherMap.getInstance().getEntity(PAGE_MISS_ID);
            if ( dest == null )
            {
                MyLogger.getNormal().error( "page miss page id[" + PAGE_MISS_ID + "] has not existed!");
                return;
            }
        }

        req.setAttribute("errMsg", errMsg);

        WebEntityContext context = new WebEntityContext();
        context.setRequest( req );
        context.setResponse( res );
        context.setId(errorEntityId);
        dest.go( context );
    }
    
    public static String getFinalId( ServletRequest request ) {
        String id = (String)request.getAttribute( "id" );
        if ( id != null && !id.equals("") ) {
            return id;
        }
        else {
            return request.getParameter( "id" );
        }
    }    
}
